package com.psmz.iwi.docanalyzer.core.document.parser.pdf;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.ContentByteUtils;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.psmz.iwi.docanalyzer.core.document.parser.Parser;
import com.psmz.iwi.docanalyzer.core.document.parser.ParserException;
import com.psmz.iwi.docanalyzer.core.document.parser.TextExtractionResult;

public class PDFParser implements Parser {

	@Override
	public TextExtractionResult extractText(File file) throws ParserException {
		Document document = new Document();
		PdfReader reader = null;
		try {
			reader = new PdfReader(new BufferedInputStream(new FileInputStream(
					file)));
			TextExtractingRenderListener listener = new TextExtractingRenderListener();
			int numberOfPages = reader.getNumberOfPages();
			for (int i = 1; i <= numberOfPages; i++) {
				PdfContentStreamProcessor processor = new PdfContentStreamProcessor(
						listener);
				PdfDictionary pageDic = reader.getPageN(i);
				PdfDictionary resourcesDic = pageDic
						.getAsDict(PdfName.RESOURCES);
				processor.processContent(
						ContentByteUtils.getContentBytesForPage(reader, i),
						resourcesDic);
			}
			return new TextExtractionResult(listener.getExtractedText());
		} catch (FileNotFoundException e) {
			throw new ParserException("Nie znaleziono pliku", e);
		} catch (IOException e) {
			throw new ParserException("Blad wejscia/wyjscia", e);
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
	}

	private static class TextExtractingRenderListener implements RenderListener {

		private StringBuilder builder = new StringBuilder();

		@Override
		public void beginTextBlock() {

		}

		@Override
		public void endTextBlock() {

		}

		@Override
		public void renderImage(ImageRenderInfo info) {

		}

		@Override
		public void renderText(TextRenderInfo info) {
			builder.append(info.getText());
			builder.append(" ");

		}

		public String getExtractedText() {
			return builder.toString();
		}

	}

}
